package com.example.template.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.template.common.constant.TokenConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: JwtUtil
 * @description: Jwt工具类
 * @author: Kuangkeli
 * @date: 2024/01/19 17:24
 **/
@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    public  String secret;

    @Value("${jwt.expire}")
    public  Integer tokenExpire;

    @Autowired
    private RedisUtil redisUtil;



    /**
     * 传入payload信息获取token
     * @param map payload
     * @return token
     */
    public  String getToken(Map<String, Object> map) {
        System.out.println(secret+tokenExpire);
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,(String) v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, tokenExpire); //默认1800秒过期
        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        String token = builder.sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 验证token 合法性
     */
    public  DecodedJWT verify(String token) {
        //如果有任何验证异常，此处都会抛出异常
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }


    //传入JWT携带的信息 与redis比对
    public boolean checkToken(String JWT,String clientType){
        if (clientType ==null || clientType.isEmpty()){
           clientType = TokenConstant.CLIENT_TYPE_WEB;
        }
        //根据JWT中解析出的token在redis中查找 如果能找到说明token正常
        Map<Object, Object> redisMap = redisUtil.hmget(getTokenInfo(JWT).get("token"));
        if (redisMap != null){
            if (redisMap.get("client_type").equals(clientType)){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取token信息方法
     */
    public Map<String, String> getTokenInfo(String token) {
        Map<String, String> tokenInfo = new HashMap<>();
        Map<String, Claim> decodedClaims = JWT.require(Algorithm.HMAC256(secret)).build().verify(token).getClaims();
        // 将解码后的声明信息存入 tokenInfo map 中
        for (Map.Entry<String, Claim> entry : decodedClaims.entrySet()) {
            String claimName = entry.getKey();
            String claimValue = entry.getValue().asString();

            tokenInfo.put(claimName, claimValue);
        }

        return tokenInfo;
    }

}
